/**
 * title:民生专题
 * author:LDM
 * date:2018/08/15
 */
// 组件
import lineBarEchart from "../../components/lineBarEchart/lineBarEchart.vue"
import barEchart from "../../components/barEchart/barEchart.vue"
import pieEchart from "../../components/pieEchart/pieEchart.vue"
import wbTab from "../../components/tab/tab.vue"
import wbHeader from "../../components/bdHeader/bdHeader.vue"
import vueUtil from "../../public/vueUtil.js";

export default {
  name: "livelihoodTheme",
  components: {
    "line-bar-echarts": lineBarEchart,
    "bar-echarts": barEchart,
    "pie-echarts": pieEchart,
    "wb-tab": wbTab,
    "wb-Header": wbHeader,
  },
  data: function () {
    return ({
      lineBarEchatData: null,
      barData: [],
      pieData: [],
      registerUserTotal: "",
      registerDateRang: {
        value: "",
        changeRurDateFunc: {
          disabledDate(time) {
            let curDate = (new Date()).getTime();
            let beingDate = (new Date("2016-08-25")).getTime();
            return time.getTime() > Date.now() || time.getTime() < beingDate;
          },
          onPick: function (e) {
            let _this = this;
            let startDate = new Date(e.minDate).getTime();
            let endDate = e.maxDate ? new Date(e.maxDate).getTime() : false;
            endDate ? vueUtil.bus.$emit("changeRurDateFunc", {
              startDate: startDate,
              endDate: endDate
            }) : {};
          }
        }

      },//用户增长趋势的的日期选择
      pieDateRang: {
        value: "",
        changeRurDateFunc: {
          disabledDate(time) {
            let curDate = (new Date()).getTime();
            let beingDate = (new Date("2016-08-25")).getTime();
            return time.getTime() > Date.now() || time.getTime() < beingDate;
          },
          onPick: function (e) {
            let _this = this;
            let startDate = new Date(e.minDate).getTime();
            let endDate = e.maxDate ? new Date(e.maxDate).getTime() : false;
            endDate ? vueUtil.bus.$emit("pieDateRangFunc", {
              startDate: startDate,
              endDate: endDate
            }) : {};
          }
        }

      },//各端访客信息的日期选择
      visitorDateRang: {
        value: "",
        changeRurDateFunc: {
          disabledDate(time) {
            let curDate = (new Date()).getTime();
            let beingDate = (new Date("2016-08-25")).getTime();
            return time.getTime() > Date.now() || time.getTime() < beingDate;
          },
          onPick: function (e) {
            let _this = this;
            let startDate = new Date(e.minDate).getTime();
            let endDate = e.maxDate ? new Date(e.maxDate).getTime() : false;
            endDate ? vueUtil.bus.$emit("visitorDateRangFunc", {
              startDate: startDate,
              endDate: endDate
            }) : {};
          }
        }

      },//访客增长趋势的的日期选择
    });
  },
  mounted: function () {
    let _this = this;
    let startDate = "";
    let endDate = "";
    let initDateRang = {
      startDate: new Date(_this.getMonthFunc(-1)).getTime(),
      endDate: new Date(_this.getMonthFunc(0)).getTime()
    };
    _this.registerDateRang.value = [initDateRang.startDate, initDateRang.endDate];
    _this.visitorDateRang.value = [initDateRang.startDate, initDateRang.endDate];
    _this.pieDateRang.value = [initDateRang.startDate, initDateRang.endDate];
    _this.getRegisterNumFunc();
    _this.getRegisterInCreaseFunc(initDateRang);
    vueUtil.bus.$on("changeRurDateFunc", function (data) {
      _this.getRegisterInCreaseFunc(data);
    });
    _this.getPieDataFunc(initDateRang);
    vueUtil.bus.$on("pieDateRangFunc", function (data) {
      _this.getPieDataFunc(data);
    });
    _this.getVisitorDataFunc(initDateRang);
    vueUtil.bus.$on("visitorDateRangFunc", function (data) {
      _this.getVisitorDataFunc(data);
    });
  },
  methods: {
    getMonthFunc: function (type) {
      let nowdate = new Date();
      nowdate.setMonth(nowdate.getMonth() + type);
      let y = nowdate.getFullYear();
      let m = nowdate.getMonth() + 1;
      let d = nowdate.getDate();
      m = ("" + m).length < 2 ? "0" + m : m;
      d = ("" + d).length < 2 ? "0" + d : d;
      let formatwdate = y + '-' + m + '-' + d;
      return formatwdate;
    },
    /**
     * 注册用户总数信息统计
     */
    getRegisterNumFunc: function () {
      let _this = this;
      let request = {
        "body": {},
        "head": {"version": "1.0"}
      };
      let tmpParams = {
        visual: 1,
        code: 'STAT001',
        request: JSON.stringify(request)
      };
      $.ajax({
        url: $.Utils.urlPath(""),
        dataType: 'json',
        type: 'get',
        data: tmpParams,
        success: function (res) {
          if (res.head.rtnCode == "000000") {
            let registerUserTotal = res.body ? res.body + "" : "0";
            let leaveZero = 8 - registerUserTotal.length;
            let zeroString = "";
            for (let rbLength = 0; rbLength < leaveZero; rbLength++) {
              zeroString = zeroString + "0";
            }
            _this.registerUserTotal = zeroString + registerUserTotal;
          } else {
            $.Utils.showBarrage("服务器异常")
          }

        },
        error: function (err) {
          $.Utils.showBarrage("服务器异常")
        }
      })
    },
    /**
     * 注册用户增长趋势数据统计接口
     */
    getRegisterInCreaseFunc: function (e) {
      let _this = this;
      let startDate = $.Utils.setDateFormat(e.startDate, "yyyy-MM-dd");
      let endDate = $.Utils.setDateFormat(e.endDate, "yyyy-MM-dd");
      let request = {
        "body": {
          "startDate": startDate,
          "gran": "day",
          "endDate": endDate
        },
        "head": {
          "version": "1.0"
        }
      };
      let tmpParams = {
        visual: 1,
        code: 'STAT002',
        request: JSON.stringify(request)
      };
      $.ajax({
        url: $.Utils.urlPath(""),
        dataType: 'json',
        type: 'get',
        data: tmpParams,
        success: function (res) {
          if (res.head.rtnCode == "000000") {
            _this.lineBarEchatData = false;
            let xData = [], yData = [];
            for (let xLength = 0; xLength < res.body.list.length; xLength++) {
              xData.push(res.body.list[xLength].date);
              yData.push(res.body.list[xLength].count);
            }
            let lineBarEchatData = {
              xData: xData,
              yData: [{
                type: "bar",
                data: yData
              }, {
                type: "line",
                data: yData
              }]
            };
            setTimeout(function () {
              _this.lineBarEchatData = lineBarEchatData;
            }, 0);
          } else {
            $.Utils.showBarrage("服务器异常")
          }
        },
        error: function (err) {
        }
      })
    },
    /**
     * 获取各端访客信息
     */
    getPieObjFunc: function (data) {
      let _this = this;
      let list = data.body.data[0].result.items[1];
      let pvObj = {
        index: _this.getDataIndexValueFunc("pv_count", data.body.data[0].result.fields),
        total: 0,
        data: []
      };
      let visitorObj = {
        index: _this.getDataIndexValueFunc("visitor_count", data.body.data[0].result.fields),
        total: 0,
        data: []
      };
      let ipObj = {
        index: _this.getDataIndexValueFunc("ip_count", data.body.data[0].result.fields),
        total: 0,
        data: []
      };
      let allTotal = 0;
      for (let lLength = 0; lLength < list.length; lLength++) {
        for (let subLength = 0; subLength < list[lLength].length; subLength++) {
          if(typeof list[lLength][subLength] =="number"){
            allTotal = allTotal + list[lLength][subLength];
            if (subLength == pvObj.index) {
              pvObj.total = pvObj.total + list[lLength][subLength];
              pvObj.data.push(list[lLength][subLength])
            }
            if (subLength == visitorObj.index) {
              visitorObj.total = visitorObj.total + list[lLength][subLength];
              visitorObj.data.push(list[lLength][subLength])
            }
            if (subLength == ipObj.index) {
              ipObj.total = ipObj.total + list[lLength][subLength];
              ipObj.data.push(list[lLength][subLength])
            }
          }
        }
      }
      pvObj.percent = $.Utils.toFixedFunc(pvObj.total / allTotal *100, 1, true);
      visitorObj.percent = $.Utils.toFixedFunc(visitorObj.total / allTotal *100, 1, true);
      ipObj.percent = $.Utils.toFixedFunc(ipObj.total / allTotal *100, 1, true);
      let params =  [{
        name: "PV总数",
        value: pvObj.percent
      }, {
        name: "IP总数",
        value: ipObj.percent
      }, {
        name: "访问数",
        value: visitorObj.percent
      }];
      return params;
    },
    getPieDataFunc: function (e) {
      let _this = this;
      let startDate = $.Utils.setDateFormat(e.startDate, "yyyyMMdd");
      let endDate = $.Utils.setDateFormat(e.endDate, "yyyyMMdd");
      let request = {
        "body": {
          "start_date": startDate,
          "gran": "day",
          "end_date": endDate
        },
        "head": {
          "version": "1.0"
        }
      };
      let tmpParams = {
        visual: 1,
        code: 'STAT003',
        request: JSON.stringify(request)
      };
      $.ajax({
        url: $.Utils.urlPath(""),
        dataType: 'json',
        type: 'get',
        data: tmpParams,
        success: function (res) {
          if (res.head.rtnCode == "000000") {
            console.log("pie");
            let app = JSON.parse(res.body.app);
            let weChart = JSON.parse(res.body.weixin);
            let portal = JSON.parse(res.body.portal);
            let pieData = [{
              title: "APP",
              data: _this.getPieObjFunc(app)
            },{
              title: "微信",
              data: _this.getPieObjFunc(weChart)
            },{
              title: "用户",
              data: _this.getPieObjFunc(portal)
            }];
            _this.pieData  = [];
            console.log(pieData);
            setTimeout(function () {
              _this.pieData = pieData;
            },0)
          } else {
            $.Utils.showBarrage("服务器异常")
          }
        },
        error: function (err) {
          $.Utils.showBarrage("服务器异常")
        }
      })
    },
    /**
     * 获取某参数对应的下标
     * @param name
     * @param data
     * @returns {number}
     */
    getDataIndexValueFunc: function (name, data) {
      let index = 0;
      for (let indexNum = 0; indexNum < data.length; indexNum++) {
        if (name == data[indexNum]) {
          index = indexNum;
          break;
        }
      }
      return index - 1;
    },
    /**
     * 获取访问增长趋势
     */
    getVisitorDataFunc: function (e) {
      let _this = this;
      let startDate = $.Utils.setDateFormat(e.startDate, "yyyyMMdd");
      let endDate = $.Utils.setDateFormat(e.endDate, "yyyyMMdd");
      let request = {
        "body": {
          "start_date": startDate,
          "gran": "day",
          "end_date": endDate
        },
        "head": {
          "version": "1.0"
        }
      };
      let tmpParams = {
        visual: 1,
        code: 'STAT004',
        request: JSON.stringify(request)
      };
      $.ajax({
        url: $.Utils.urlPath(""),
        dataType: 'json',
        type: 'get',
        data: tmpParams,
        success: function (res) {
          if (res.head.rtnCode == "000000") {
            let data = JSON.parse(res.body.trend).body.data[0].result;
            //构造xData
            let xData = [];
            for (let xLength = (data.items[0].length - 1); xLength >= 0; xLength--) {
              xData = xData.concat(data.items[0][xLength]);
            }
            for (let xLength = 0; xLength < xData.length; xLength++) {
              xData[xLength] = xData[xLength].split("/").join("-")
            }
            let pvObj = {
              name: "PV总数",
              index: _this.getDataIndexValueFunc("pv_count", data.fields),
              data: []
            };
            let visitorObj = {
              name: "访问次数",
              index: _this.getDataIndexValueFunc("visitor_count", data.fields),
              data: []
            };
            let newVisitorObj = {
              name: "新访客数",
              index: _this.getDataIndexValueFunc("new_visitor_count", data.fields),
              data: []
            };
            let ipObj = {
              name: "IP总数",
              index: _this.getDataIndexValueFunc("ip_count", data.fields),
              data: []
            };
            for (let yLength = 0; yLength < data.items[1].length; yLength++) {
              for (let subYLength = 0; subYLength < data.items[1][yLength].length; subYLength++) {
                if (pvObj.index == subYLength) {
                  pvObj.data.push(data.items[1][yLength][subYLength]);
                }
                if (visitorObj.index == subYLength) {
                  visitorObj.data.push(data.items[1][yLength][subYLength]);
                }
                if (newVisitorObj.index == subYLength) {
                  newVisitorObj.data.push(data.items[1][yLength][subYLength]);
                }
                if (ipObj.index == subYLength) {
                  ipObj.data.push(data.items[1][yLength][subYLength]);
                }
              }
            }
            let barData = [{
              title: pvObj.name,
              dw: "单位:人次",
              xData: xData,
              yData: [{
                color: "#40a3da",
                data: pvObj.data
              }]
            }, {
              title: visitorObj.name,
              dw: "单位:人次",
              xData: xData,
              yData: [{
                color: "#ffef3a",
                data: visitorObj.data
              }]
            }, {
              title: newVisitorObj.name,
              dw: "单位:人次",
              xData: xData,
              yData: [{
                color: "#d54c98",
                data: newVisitorObj.data
              }]
            }, {
              title: ipObj.name,
              dw: "单位:人次",
              xData: xData,
              yData: [{
                color: "#46dca9",
                data: ipObj.data
              }]
            }];
            _this.barData = [];
            setTimeout(function () {
              _this.barData = barData;
            }, 0);
          } else {
            $.Utils.showBarrage("服务器异常")
          }
        },
        error: function (err) {
          $.Utils.showBarrage("服务器异常")
        }
      })
    }
  }
}
